package com.java2207.group1.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.builder.ExcelWriterSheetBuilder;
import com.java2207.group1.bo.AssetsBo;
import com.java2207.group1.bo.ExpenditureBo;
import com.java2207.group1.bo.IncomeBo;
import com.java2207.group1.bo.MonthBo;
import com.java2207.group1.common.LayuiPageVo;
import com.java2207.group1.common.R;
import com.java2207.group1.listener.ExpenditureExcelListener;
import com.java2207.group1.listener.IncomeExcelListener;
import com.java2207.group1.pojo.Assets;
import com.java2207.group1.pojo.Expenditure;
import com.java2207.group1.pojo.Income;
import com.java2207.group1.service.FinancialManagementService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

/**
 * @author HuiCL
 * @version 1.02
 * @date 2022/7/25 17:48
 */
@RestController
@RequestMapping("/assets")
public class FinancialManagementController {

    @Autowired
    private FinancialManagementService financialManagementServiceImpl;

    //----------------------------------income表-----------------------------------------//
    // 资金收入分页列表
    @RequestMapping("/incomeList")
    public LayuiPageVo<Income> incomeList(@RequestParam Map<String,Object> params) {
        LayuiPageVo<Income> incomeLayuiPageVo = financialManagementServiceImpl.incomePageData(params);

        return incomeLayuiPageVo;
    }



    // 添加资金收入
    @RequestMapping("/addIncome")
    public R addIncome(Income income) {
        int result = financialManagementServiceImpl.addIncome(income);
        if (result == 1) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    // 修改资金收入
    @RequestMapping("/updateIncome")
    public R updateIncome(Income income) {
        int result = financialManagementServiceImpl.updateIncome(income);
        if (result == 1) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @RequestMapping("/deleteIncome")
    @ResponseBody
    public R deleteIncomeById(@RequestParam("id") int id) {
        int result = financialManagementServiceImpl.deleteIncomeById(id);
        if (result == 1) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    // 批量删除Income
    @RequestMapping("/batchRemoveIncome")
    public R batchRemoveIncome(@RequestBody(required=false) List<Integer> list) {
        if(null == list){
            return R.error();
        }

        if (list.isEmpty()) {
            return R.error().message("未选择数据");
        } else {
            int number = financialManagementServiceImpl.batchRemoveIncome(list);
            return R.ok().message("删除了" + number + "条数据").code(200);
        }
    }


    //下载income表的excel 模板
    @RequestMapping("/incomeTemplateDownload")
    public void incomeTemplateDownload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //下载excel 的 响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //读取服务器上的模板文件 写到浏览器
        //得到模板文件的路径
        String realPath = request.getServletContext().getRealPath("/template/资金收入表模板.xlsx");

        //根据文件路径 创建File 对象
        File file = new File(realPath);

        // 把File  对象转为 字节数组
        byte[] bytes = FileUtils.readFileToByteArray(file);
        // 下载的文件名 是中文  要进行转码  要不然会出现乱码
        String filename = URLEncoder.encode("资金收入表模板", "utf-8");

        // 告诉浏览器  下载文件
        response.setHeader("Content-Disposition","attachment;filename=" + filename + ".xlsx");

        //得到指向浏览器的输出流  向浏览器写输出
        ServletOutputStream outputStream = response.getOutputStream();
        // 把字节数组 输出到浏览器
        outputStream.write(bytes);

        outputStream.close();
    }

    @Autowired
    private IncomeExcelListener incomeExcelListener;

    @PostMapping("/importIncome")
    @ResponseBody
    public R importData(MultipartFile file, HttpServletResponse resp) throws IOException {
        if (file != null) {
            ExcelReaderBuilder read = EasyExcel.read(file.getInputStream(), IncomeBo.class, incomeExcelListener);
            ExcelReaderSheetBuilder sheet = read.sheet();

            sheet.doRead();
        }

        return R.ok();
    }


    //导出列表数据     把满足条件的数据 查询出来  写到excel 中  ，把excel 写到浏览器
    @RequestMapping("/exportIncome")
    public void export(Income income, HttpServletResponse response) throws IOException {
        //下载excel 的 响应数据格式
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 下载的文件名 是中文  要进行转码  要不然会出现乱码
        String filename = URLEncoder.encode("资金收入记录", "utf-8");

        // 告诉浏览器  下载文件
        response.setHeader("Content-Disposition","attachment;filename="+filename+".xlsx");

        //得到指向浏览器的输出流  向浏览器写输出
        ServletOutputStream outputStream = response.getOutputStream();

        ExcelWriterBuilder write = EasyExcel.write(outputStream, IncomeBo.class);

        ExcelWriterSheetBuilder sheet = write.sheet();
        //准备满足条件的集合数据
        List<IncomeBo> incomeBoList =   financialManagementServiceImpl.incomeExcelData(income);
        // 把这个集合数据 写到 输出流
        sheet.doWrite(incomeBoList);
    }


    //--------------------------------expenditure表--------------------------------------------------//
    // 资金支出表分页列表
    @RequestMapping("/expenditureList")
    public LayuiPageVo<Expenditure> expenditureList(@RequestParam Map<String,Object> params) {
        LayuiPageVo<Expenditure> expenditureLayuiPageVo = financialManagementServiceImpl.expenditurePageData(params);

        return expenditureLayuiPageVo;
    }


    // 添加资金支出
    @RequestMapping("/addExpenditure")
    public R addExpenditure(Expenditure expenditure) {
        int result = financialManagementServiceImpl.addExpenditure(expenditure);
        if (result == 1) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    // 修改资金支出
    @RequestMapping("/updateExpenditure")
    public R updateExpenditure(Expenditure expenditure) {
        int result = financialManagementServiceImpl.updateExpenditure(expenditure);
        if (result == 1) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @RequestMapping("/deleteExpenditure")
    @ResponseBody
    public R deleteExpenditureById(@RequestParam("id") int id) {
        int result = financialManagementServiceImpl.deleteExpenditureById(id);
        if (result == 1) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    // 批量删除Expenditure
    @RequestMapping("/batchRemoveExpenditure")
    public R batchRemoveExpenditure(@RequestBody(required=false) List<Integer> list) {
        if(null == list){
            return R.error();
        }

        if (list.isEmpty()) {
            return R.error().message("未选择数据");
        } else {
            int number = financialManagementServiceImpl.batchRemoveExpenditure(list);
            return R.ok().message("删除了" + number + "条数据").code(200);
        }
    }



    //下载expenditure表的excel 模板
    @RequestMapping("/expenditureTemplateDownload")
    public void expenditureTemplateDownload(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //下载excel 的 响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //读取服务器上的模板文件 写到浏览器
        //得到模板文件的路径
        String realPath = request.getServletContext().getRealPath("/template/资金支出表模板.xlsx");

        //根据文件路径 创建File 对象
        File file = new File(realPath);

        // 把File  对象转为 字节数组
        byte[] bytes = FileUtils.readFileToByteArray(file);
        // 下载的文件名 是中文  要进行转码  要不然会出现乱码
        String filename = URLEncoder.encode("资金支出表模板", "utf-8");

        // 告诉浏览器  下载文件
        response.setHeader("Content-Disposition","attachment;filename=" + filename + ".xlsx");

        //得到指向浏览器的输出流  向浏览器写输出
        ServletOutputStream outputStream = response.getOutputStream();
        // 把字节数组 输出到浏览器
        outputStream.write(bytes);

        outputStream.close();
    }

    @Autowired
    private ExpenditureExcelListener expenditureExcelListener;

    @PostMapping("/importExpenditure")
    @ResponseBody
    public R importExpenditureData(MultipartFile file, HttpServletResponse resp) throws IOException {
        if (file != null) {
            ExcelReaderBuilder read = EasyExcel.read(file.getInputStream(), ExpenditureBo.class, expenditureExcelListener);
            ExcelReaderSheetBuilder sheet = read.sheet();

            sheet.doRead();
        }

        return R.ok();
    }


    //导出列表数据     把满足条件的数据 查询出来  写到excel 中  ，把excel 写到浏览器
    @RequestMapping("/exportExpenditure")
    public void exportExpenditure(Expenditure expenditure, HttpServletResponse response) throws IOException {
        //下载excel 的 响应数据格式
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 下载的文件名 是中文  要进行转码  要不然会出现乱码
        String filename = URLEncoder.encode("资金支出记录", "utf-8");

        // 告诉浏览器  下载文件
        response.setHeader("Content-Disposition","attachment;filename="+filename+".xlsx");

        //得到指向浏览器的输出流  向浏览器写输出
        ServletOutputStream outputStream = response.getOutputStream();

        ExcelWriterBuilder write = EasyExcel.write(outputStream, ExpenditureBo.class);

        ExcelWriterSheetBuilder sheet = write.sheet();
        //准备满足条件的集合数据
        List<ExpenditureBo> expenditureBoList =   financialManagementServiceImpl.expenditureExcelData(expenditure);
        // 把这个集合数据 写到 输出流
        sheet.doWrite(expenditureBoList);
    }



    //**************************************Assets表*********************************************************//

    // 资金账户表分页列表
    @RequestMapping("/assetsList")
    public LayuiPageVo<Assets> assetsList(@RequestParam Map<String,Object> params) {
        LayuiPageVo<Assets> assetsLayuiPageVo = financialManagementServiceImpl.assetsPageData(params);

        return assetsLayuiPageVo;
    }


    // 添加资金账户记录
    @RequestMapping("/addAssets")
    public R addAssets(Assets assets) {
        int result = financialManagementServiceImpl.addAssets(assets);
        if (result == 1) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    // 修改资金账户的支出
    @RequestMapping("/updateAssets")
    public R updateAssets(Assets assets) {
        System.out.println("修改资金时, 接收到的assets为: " + assets);
        int result = financialManagementServiceImpl.updateAssets(assets);
        if (result == 1) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    @RequestMapping("/deleteAssets")
    public R deleteAssetsById(@RequestParam("id") int id) {
        int result = financialManagementServiceImpl.deleteAssetsById(id);
        if (result == 1) {
            return R.ok();
        } else {
            return R.error();
        }
    }

    // 批量删除Assets
    @RequestMapping("/batchRemoveAssets")
    public R batchRemoveAssets(@RequestBody(required=false) List<Integer> list) {
        if(null == list){
            return R.error();
        }

        if (list.isEmpty()) {
            return R.error().message("未选择数据");
        } else {
            int number = financialManagementServiceImpl.batchRemoveAssets(list);
            return R.ok().message("删除了" + number + "条数据").code(200);
        }
    }


    //导出列表数据     把满足条件的数据 查询出来  写到excel 中  ，把excel 写到浏览器
    @RequestMapping("/exportAssets")
    public void exportAssets(Assets assets, HttpServletResponse response) throws IOException {
        //下载excel 的 响应数据格式
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        // 下载的文件名 是中文  要进行转码  要不然会出现乱码
        String filename = URLEncoder.encode("财务报表信息", "utf-8");

        // 告诉浏览器  下载文件
        response.setHeader("Content-Disposition","attachment;filename="+filename+".xlsx");

        //得到指向浏览器的输出流  向浏览器写输出
        ServletOutputStream outputStream = response.getOutputStream();

        ExcelWriterBuilder write = EasyExcel.write(outputStream, AssetsBo.class);

        ExcelWriterSheetBuilder sheet = write.sheet();
        //准备满足条件的集合数据
        List<AssetsBo> assetsBoList =   financialManagementServiceImpl.assetsExcelData(assets);
        // 把这个集合数据 写到 输出流
        sheet.doWrite(assetsBoList);
    }

    /**********************************************************************************************/

    // 得到每年的月盈利与月支出的柱状图
    @RequestMapping("/yearlyFinancialStatements")
    public LayuiPageVo<MonthBo> yearlyIncomeAndExpenditure(String year) {
        List<MonthBo> monthBoList = financialManagementServiceImpl.yearlyFinancialStatements(year);
        int maximumForYAxis = financialManagementServiceImpl.maximumForYAxis(monthBoList);

        LayuiPageVo<MonthBo> monthBoLayuiPageVo = new LayuiPageVo<>();

        monthBoLayuiPageVo.setCode(maximumForYAxis);
        monthBoLayuiPageVo.setData(monthBoList);

        return monthBoLayuiPageVo;
    }



}
